package com.chaochis.wind.base_controller;

import com.chaochis.wind.base_config.page_config.api.ApiResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * 处理controller返回结果的增强类
 * @author 刘超/chaochis
 */
@RestControllerAdvice
public class CommonResponseController implements ResponseBodyAdvice<Object> {

  @Autowired
  private ObjectMapper objectMapper;

  @Override
  public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
    var returnMethod = Objects.requireNonNull(returnType.getMethod()).getReturnType();
    var is = returnMethod.getName().equals(ApiResult.class.getName());
    return !is;
  }

  @Override
  public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    assert body != null;
    if (body instanceof String) {
      try {
        return this.handleString(body);
      } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
      }
    } else {
      return body;
    }
  }
  
  private Object handleString(Object body) throws JsonProcessingException {
    return this.objectMapper.writeValueAsString(ApiResult.success(body));
  }
}
